package main

import (
	"net"
)

type TcpServerEx struct {
	OnNewConnect func(client *TcpClientEx)              // 新连接事件
	OnDisconnect func(client *TcpClientEx)              // 断开连接事件
	OnMsgReceive func(client *TcpClientEx, bmsg []byte) // 收到消息事件
}

func NewTcpServer() *TcpServerEx {
	server := TcpServerEx{}
	return &server
}

func (this *TcpServerEx) Listen(port int) {
	ln, err := net.ListenTCP("tcp", &net.TCPAddr{Port: port})
	if err != nil {
		panic("监听失败")
		return
	}
	// 监听携程
	go func() {
		defer ln.Close()

		for {
			conn, err := ln.AcceptTCP()
			if err != nil {
				continue
			}
			client := AttachTcpClient(conn)
			client.OnDisconnect = func() {
				if this.OnDisconnect != nil {
					this.OnDisconnect(client)
				}
			}
			client.OnMsgReceive = func(msg []byte) {
				if this.OnMsgReceive != nil {
					this.OnMsgReceive(client, msg)
				}
			}
			// 接收到新连接的通知
			if this.OnNewConnect != nil {
				this.OnNewConnect(client)
			}
		}
	}()
}
